package http;

import java.io.IOException;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

/**
 * 模拟浏览器请求的工具类,用于调用接口,参数是json数据
 * 
 * @author gj
 * 
 */
public class HttpClientUtil {

	private static BasicCookieStore cookieStore = new BasicCookieStore();
	private static RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.DEFAULT).build();
	private static CloseableHttpClient commonHttpclient = HttpClients.custom().setDefaultRequestConfig(globalConfig).setDefaultCookieStore(cookieStore).build();

	private static final Log log = LogFactory.getLog(HttpClientUtil.class);

	public static String sendPost(String url, List<NameValuePair> nvps, String preInfo) throws ClientProtocolException, IOException {
		HttpPost httpPost = new HttpPost(url);
		if (nvps != null) {
			httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
		}
		httpPost.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.79 Safari/537.36");
		httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
		httpPost.setHeader("Connection", "keep-alive");
		httpPost.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
		CloseableHttpResponse response = commonHttpclient.execute(httpPost);
		String responseMessage = EntityUtils.toString(response.getEntity(), "UTF-8");
		log.info(preInfo + ": " + responseMessage);
		return responseMessage;
	}

	public static String sendGet(String url, List<NameValuePair> nvps) {
		HttpGet httpGet = new HttpGet(url);
		String responseMessage = "";
		try {
			CloseableHttpResponse response = commonHttpclient.execute(httpGet);
			responseMessage = EntityUtils.toString(response.getEntity(), "UTF-8");
			log.info("sendGet: " + responseMessage);
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (ParseException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return responseMessage;
	}

	public static void main(String[] args) {
		HttpClientUtil.sendGet("https://my.oschina.net/chaoren8/admin/new-project", null);
	}

}
